package org.september.pisces.filestore.service;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import org.september.core.component.ApplicationContextHolder;
import org.september.core.component.log.LogHelper;
import org.september.core.exception.BusinessException;
import org.september.pisces.filestore.api.FileStoreService;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.entity.FileStorePool;
import org.september.pisces.filestore.enums.StorePoolTypeEnum;
import org.september.pisces.filestore.service.hik.HikPoolService;
import org.september.smartdao.CommonDaoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class FileStoreManager {

    @Value("${hik.oss.ip:}")
    private String ip;
    @Value("${hik.oss.port:}")
    private String port;
    @Value("${hik.oss.accessKey:}")
    private String accessKey;
    @Value("${hik.oss.secretKey:}")
    private String secretKey;

    @Autowired
    private HikPoolService hikPoolService;

    public static List<FileStorePool> allPool = null;

    protected LogHelper log = LogHelper.getLogger(this.getClass());

    private static final String Default_Pool_Name = "_default";

    public FileStoreItem save(String poolName, byte[] data, String ext, boolean needThumb, Float thumbRate) {
        if (!StringUtils.hasText(poolName)) {
            poolName = Default_Pool_Name;
        }
        FileStoreItem item = new FileStoreItem();
        FileStorePool pool = getPool(poolName);
        if (pool.getStoreType() == null) {
            throw new BusinessException("存储池" + poolName + "类型配置错误");
        }
        String path = getFileStoreService(pool.getStoreType()).saveWithThumb(pool, data, ext, needThumb, thumbRate);
        item.setFileUUID(UUID.randomUUID().toString());
        item.setPath(path);
        item.setExt(ext);
        item.setPoolId(pool.getId());
        CommonDaoHolder.getCommonDao().save(item);
        return item;
    }

    public InputStream getInputStreamByUUID(FileStoreItem po, boolean thumb) {
        if (po == null) {
            throw new BusinessException("文件存储池不存在或配置错误");
        }
        FileStorePool pool = CommonDaoHolder.getCommonDao().get(FileStorePool.class, po.getPoolId());
        return getFileStoreService(pool.getStoreType()).getInputStream(pool, po, thumb);
    }

    public FileStoreItem getFileItem(String uuid) {
        if (!StringUtils.hasText(uuid)) {
            throw new BusinessException("文件不存在,uuid=" + uuid);
        }
        FileStoreItem item = new FileStoreItem();
        item.setFileUUID(uuid);
        item.setDeleteFlag(0);
        FileStoreItem po = CommonDaoHolder.getCommonDao().getByExample(item);
        if (po == null) {
            return null;
        }
        return po;
    }

//	public String getHttpPath(String uuid) {
//		FileStoreItem item = new FileStoreItem();
//		item.setFileUUID(uuid);
//		item.setDeleteFlag(0);
//		FileStoreItem po = dao.getByExample(item);
//		if(po==null) {
//			return "/404";
//		}
//		FileStorePool pool = dao.get(FileStorePool.class, po.getPoolId());
//		return "/file/" + pool.getPoolName()+"/"+po.getPath();
//	}

    private FileStorePool getPool(String poolName) {
        FileStorePool vo = new FileStorePool();
        vo.setPoolName(poolName);
        vo.setDeleteFlag(0);
        return CommonDaoHolder.getCommonDao().getByExample(vo);
    }

    public void getAllPool() {
        FileStorePool vo = new FileStorePool();
        vo.setDeleteFlag(0);
        allPool = CommonDaoHolder.getCommonDao().listByExample(vo);
    }


    private FileStoreService getFileStoreService(int type) {
        if (StorePoolTypeEnum.本地磁盘.code == type) {
            return ApplicationContextHolder.getContext().getBean(DiskFileStoreService.class);
        } else if (StorePoolTypeEnum.HIK.code == type) {
            return ApplicationContextHolder.getContext().getBean(HikFileStoreService.class);
        } else {
            throw new BusinessException("不支持的存储池类型");
        }
    }

    public void initDefaultPool() {
        FileStorePool po = getPool(Default_Pool_Name);
        if (po == null) {
            FileStorePool vo = new FileStorePool();
            vo.setPoolName(Default_Pool_Name);
            vo.setDeleteFlag(0);
            vo.setStoreType(StorePoolTypeEnum.本地磁盘.code);
            vo.setDiskPath("/_default_pool/");
            CommonDaoHolder.getCommonDao().save(vo);
        } else {
            getAllPool();
        }
        if (StringUtils.hasText(ip) && StringUtils.hasText(port)
                && StringUtils.hasText(accessKey) && StringUtils.hasText(secretKey)) {
            hikPoolService.initPoolSetting();
        }
    }

    public void deleteFile(String fileUuid) {
    	try {
	        FileStoreItem item = new FileStoreItem();
	        item.setFileUUID(fileUuid);
	        item.setDeleteFlag(0);
	        FileStoreItem po = CommonDaoHolder.getCommonDao().getByExample(item);
	        if (po == null) {
	            return;
	        }
	        CommonDaoHolder.getCommonDao().delete(po);
	        FileStorePool pool = CommonDaoHolder.getCommonDao().get(FileStorePool.class, po.getPoolId());
	        if (pool == null) {
	            return;
	        }
	        getFileStoreService(pool.getStoreType()).deleteFile(pool, po);
    	}catch(Exception ex) {
    		log.getBuilder().warn("删除文件失败：uuid="+fileUuid,ex);
    	}
    }
}
